from tablestore import *

from GKModel.BaseModel import BaseModel
from GKModel.Client import Client
from GKModel.Category import Category
from GKModel.Category import CATEGORY_TUTOR


class Tutor(BaseModel):
    TABLE_NAME = 'Tutors'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.__client = Client(**kwargs)
        self.__category = Category(**kwargs)

    def query_tutor_list(self, tutor_type: str=None, next_start_primary_key=None, limit=10):
        if tutor_type is None:
            cid_start = INF_MAX
            cid_end = INF_MIN
        elif tutor_type.lower() == 'golden':
            category = self.__category.query_by_key_name(CATEGORY_TUTOR, 'System', 'Golden')
            cid_start = category['cid']
            cid_end = category['cid']
        elif tutor_type.lower() == 'normal':
            category = self.__category.query_by_key_name(CATEGORY_TUTOR, 'System', 'Normal')
            cid_start = category['cid']
            cid_end = category['cid']
        else:
            cid_start = INF_MIN
            cid_end = INF_MAX

        inclusive_start_primary_key = [('category_id', cid_start), ('tid', INF_MIN)] \
            if next_start_primary_key is None \
            else next_start_primary_key
        exclusive_end_primary_key = [('category_id', cid_end), ('tid', INF_MAX)]
        columns_to_get = []

        try:
            consumed, next_start_primary_key, row_list, next_token = self.ots_client.get_range(
                table_name=Tutor.TABLE_NAME,
                direction=Direction.BACKWARD,
                inclusive_start_primary_key=inclusive_start_primary_key,
                exclusive_end_primary_key=exclusive_end_primary_key,
                columns_to_get=columns_to_get,
                limit=limit,
                max_version=1
            )

            result = []
            for row in row_list:
                item = dict(row.primary_key)
                for att in row.attribute_columns:
                    item[att[0]] = att[1]
                result.append(item)

            return result, next_start_primary_key, self.__client.update_token()
        except OTSServiceError as e:
            raise ValueError(1000022, e.get_error_message())
        except OTSClientError as e:
            raise ValueError(1000021, e.get_error_message())

    def query_tutor(self, category_id: int, tid: int):
        primary_key = [('category_id', category_id), ('tid', tid)]

        try:
            consumed, return_row, next_token = self.ots_client.get_row(
                table_name=Tutor.TABLE_NAME,
                primary_key=primary_key,
                columns_to_get=[],
                column_filter=None,
                max_version=1
            )
            data = {
                'category_id': category_id,
                'tid': tid
            }
            for item in return_row.attribute_columns:
                data[item[0]] = item[1]

            return data, self.__client.update_token()
        except OTSClientError as e:
            raise ValueError(1000011, e.get_error_message())
        except OTSServiceError as e:
            raise ValueError(1000012, e.get_error_message())


def new(**kwargs) -> Tutor:
    return Tutor(**kwargs)
